package timing.ukulele.third.controller.msg;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import timing.ukulele.common.data.ResponseData;
import timing.ukulele.data.third.view.msg.AliyunMessageTemplateParamVO;
import timing.ukulele.data.third.view.msg.AliyunMessageTemplateVO;
import timing.ukulele.third.msgChannel.model.account.sms.ALYSmsAccount;
import timing.ukulele.third.msgChannel.utils.AccountUtils;
import timing.ukulele.third.persistent.msg.MessageTemplate;
import timing.ukulele.third.service.msg.MessageTemplateService;
import timing.ukulele.third.util.StringExtractor;
import java.util.ArrayList;
import java.util.List;

/**
 * 阿里云短信模板
 * @author
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/msg/aliyunSms")
public class AliyunMessageTemplateController {

    private final AccountUtils accountUtils;

    private final MessageTemplateService messageTemplateService;

    /**
     * 获取阿里云短信模板数据，转为系统所需格式
     * @param accountId
     * @return
     */
    public ResponseData<List<AliyunMessageTemplateVO>> getAliyunToSysMsgTemplateList(@RequestParam Long accountId, Long sysTemplateId) {
        // 构造返回值
        List<AliyunMessageTemplateVO> result = new ArrayList<>();

        // 如果系统模板ID不为空，那么查询系统模板
        MessageTemplate sysMessageTemplate = null;
        AliyunMessageTemplateVO aliyunMessageTemplateVO = null;
        if(sysTemplateId != null) {
            sysMessageTemplate = messageTemplateService.getById(sysTemplateId);
            aliyunMessageTemplateVO = JSON.parseObject(sysMessageTemplate.getMsgContent(), AliyunMessageTemplateVO.class);
        }
        // 获取阿里云短信模板数据，并转为系统所需格式
        try {
            CommonResponse response = requestAliyun(accountId);
            String data = response.getData();
            JSONObject jsonObject = JSONObject.parseObject(data);
            JSONArray jsonArray = jsonObject.getJSONArray("SmsTemplateList");

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject itemJson = jsonArray.getJSONObject(i);
                // 排除掉未审核通过的模板
                if (!itemJson.getString("AuditStatus").equals("AUDIT_STATE_PASS")) {
                    continue;
                }
                AliyunMessageTemplateVO itemVo = new AliyunMessageTemplateVO();
                if(sysMessageTemplate != null && itemJson.getString("TemplateCode").equals(aliyunMessageTemplateVO.getTemplateId())) {
                    itemVo = aliyunMessageTemplateVO;
                    itemVo.setId(itemJson.getString("TemplateCode"));
                    itemVo.setName(itemJson.getString("TemplateName"));
                }else{
                    itemVo.setId(itemJson.getString("TemplateCode"));
                    itemVo.setName(itemJson.getString("TemplateName"));
                    String templateContent = itemJson.getString("TemplateContent");
                    itemVo.setContent(templateContent);
                    // 解析短信内容中的可变参数
                    List<String> paramFiled = StringExtractor.extractContent(templateContent, "{", "}");
                    List<AliyunMessageTemplateParamVO> paramList = new ArrayList<>();
                    for (String key : paramFiled) {
                        AliyunMessageTemplateParamVO itemKey = new AliyunMessageTemplateParamVO();
                        itemKey.setKey(key);
                        itemKey.setLabel(key);
                        paramList.add(itemKey);
                    }
                    itemVo.setParamList(paramList);
                }
                result.add(itemVo);
            }
            return ResponseData.success(result);
        } catch (ClientException e) {
            return ResponseData.error("获取阿里云短信模板失败："+e.getMessage());
        }
    }

    /**
     * 请求阿里云方法
     * @param accountId
     * @return
     * @throws ClientException
     */
    private CommonResponse requestAliyun(Long accountId) throws ClientException {
        // 获取账号配置信息
        ALYSmsAccount alySmsAccount = accountUtils.getAccountById(accountId, ALYSmsAccount.class);
        // 构建阿里云请求client
        DefaultProfile profile = DefaultProfile.getProfile(alySmsAccount.getRegionId(), alySmsAccount.getAccessKeyId(), alySmsAccount.getSecret());
        IAcsClient client = new DefaultAcsClient(profile);

        // 请求阿里云获取短信模板数据
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(alySmsAccount.getUrl());
        request.setSysVersion(alySmsAccount.getSysVersion());
        request.putQueryParameter("RegionId", alySmsAccount.getRegionId());
        request.setSysAction("QuerySmsTemplateList");
        // 多个接收者用逗号相隔
        request.putQueryParameter("PageIndex", "1");
        request.putQueryParameter("PageSize", "50");

        return client.getCommonResponse(request);
    }

}
